<!--
Project Alias - Rename your assistant and makes sure it never listens.
Copyright (C) 2020  Bjørn Karmann & Tore Knudsen

This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with this program.  If not, see <https://www.gnu.org/licenses/>.
-->

<!DOCTYPE html>
<html lang="">
  <head>
    <meta name="apple-mobile-web-app-capable" content="yes">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0">
    <link rel="stylesheet" type="text/css" href="../static/style/style.css">
    <!-- <link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.7.0/css/all.css" integrity="sha384-lZN37f5QGtY3VHgisS14W3ExzMWZxybE1SJSEsQp9S+oqd12jhcu+A56Ebc1zFSJ" crossorigin="anonymous"> -->
    <title>PROJECT ALIAS</title>
    <script type="text/javascript" src="../static/js/jquery.min.js"></script>
    <script type="text/javascript" src="../static/js/jquery-color-min.js"></script>
    <script type="text/javascript" src="../static/js/rangetouch.js">></script>
    <script type="text/javascript" src="../static/js/socket.io.js"></script>
    <script type="text/javascript" src="../static/js/bodyScrollLock.js"></script>
  </head>

  <body oncontextmenu="false" onload="requestSettings()">
    <div id="app-wrapper">
      <div id="header">
        <img id="settings-icon" src="../static/assets/settings.png" onclick="openSettings()">
        <p>PROJECT ALIAS</p>
      </div>
      <div id="inner-scrool">

        <div id="blocks">
          <form id="base_block" class="block">
            <img style="display: none" id="close-icon" src="../static/assets/close.png" onclick="removeBlock(this)">
            <p>FOR ALIAS</p>
            <input class="text-input" type="text" name="input" onkeypress="checkInput(this)" value="Hi Alias"/>
            <p>FOR ASSISTANT</p>
            <textarea class="text-input" rows="1" name="output" onkeypress="checkInput(this)">Ok Google</textarea>


              <div class="line"></div>
              <div>
                <p class="sensitivity-section"> SENSITIVITY: </p> <p id="sensitivity">25</p>
                <div class="sensitivity-button">
                  <img id="arrow-down"  style="margin-right: 24px" src="../static/assets/downarrow.svg"></img>
                  <img id="arrow-up" style="margin-right: 4px"  src="../static/assets/uparrow.svg"></img>
                  <div class="clickarea" onclick="setSensitivity(this, 'up')" style="left: 36px; top:-11px;" ></div>
                  <div class="clickarea" onclick="setSensitivity(this, 'down')" style="right: 38px; top:-11px;"></div>
                </div>
              </div>


          </form>


        </div>

      <p style="text-align: center;">
          <img id="plus-icon" src="../static/assets/plus.png" onclick="addNewBlock()">
      </p>

    </div>

    <div id="footer" onclick="updateButton()">
        <div id="submit">Update Alias</div>
      </p>
    </div>

    <div id="settings">
      <div id="header">
        <img id="close-setting" src="../static/assets/close.png" onclick="closeSettings()">
        <p>SETTINGS</p>
      </div>
      <div style="padding: 15px; margin-Bottom: 32px;">
        <p style="width:100%; max-width:360px;">FOR ALIAS is what you say, FOR ASSISTANT is what Alias whispers to your device. We recommend trigger words with at least 3 syllables.</p>
      </div>

      <div class="setting-input">
        <div class="setting-title">Gender</div>
        <div class="setting-value">
          <select id="gender">
            <option value="Male">Male</option>
            <option value="Female">Female</option>
          </select>
        </div>
      </div>

      <div class="setting-input">
        <div class="setting-title">Language</div>
        <div class="setting-value">
          <select id="language">
            <option value="Afrikaans">Afrikaans</option>
            <option value="Croatian">Croatian</option>
            <option value="Czech">Czech</option>
            <option value="Danish">Danish</option>
            <option value="Dutch">Dutch</option>
            <option value="English">English</option>
            <option value="Esperanto">Esperanto</option>
            <option value="Finnish">Finnish</option>
            <option value="French">French</option>
            <option value="German">German</option>
            <option value="Greek">Greek</option>
            <option value="Hungarian">Hungarian</option>
            <option value="Italian">Italian</option>
            <option value="Mandarin">Mandarin</option>
            <option value="Polish">Polish</option>
            <option value="Spanish">Spanish</option>
            <option value="Portuguese">Portuguese</option>
            <option value="Swedish">Swedish</option>
            <option value="Swahihi">Swahihi</option>
          </select>
        </div>
      </div>

      <div class="setting-input">
        <div class="setting-title">Noise</div>
          <div class="setting-value">
            <label class="switch">
              <input id="noise" type="checkbox" checked>
              <span class="toogle round"></span>
            </label>
          </div>
      </div>

      <div style="height: 32px;"></div>
      <div class="setting-input" class="slider">
        <div class="setting-title">Volume</div>
        <div class="setting-value">10</div>
        <input class="slider" id="setting-volume" type="range" value="40" max="100"></input>
      </div>

      <div style="height: 32px;"></div>
      <div class="setting-input" class="slider">
        <div class="setting-title">Noise delay</div>
        <div class="setting-value">10s</div>
        <input class="slider" id="setting-delay" type="range" value="10" max="30"></input>
      </div>
      <div style="height: 68px;"></div>
      <div class="setting-input">
        <div class="setting-title" id="setting-default" >Set to default</div>
        <div class="setting-value" style="width: 162px;">
        </div>
        <div style="height: 15px;"></div>
      </div>
    </div>

  </body>

  <!-- Javascript -->
  <script type="text/javascript" charset="utf-8">

    const ranges = RangeTouch.setup('input[type="range"]', { thumbWidth: 20 });
    const targetElement = document.querySelector("#inner-scrool #settings");
    bodyScrollLock.disableBodyScroll(targetElement);
    var hasRecievedBlocks = false;

    // Get data form Raspberry
    var socket = io.connect('http://' + document.domain + ':' + location.port + '/socket');
    var currentSettings;


    // get message from pi
    socket.on('response', function(msg) {
      if(!hasRecievedBlocks){
        currentSettings = msg;
        updateBlocks(msg);
        updateSettings(msg);

        //prevet duplication of blocks on multiple clients.
        hasRecievedBlocks = true;
      }
    });

    //Animate block when keyword is activated
    socket.on('activated', function(msg){

      $('#blocks').children('.block').each(function () {
        var name = $(this).find('input').val(); //

        if(msg.toLowerCase() === name.toLowerCase()){
           animateblock(this, 0, 1000);
        }
      })
    })

   function animateblock(that, delay, duration){
     setTimeout(function () {
       $(that).css("background-color", "#ffc700");
       $(that).find('p').css('color','white');
       $(that).find('.line').css('background-color', 'white')
       $(that).animate({backgroundColor:"#fff"},duration);
       $(that).find('p').animate({color: '#808080'},duration);
       $(that).find('.line').animate({backgroundColor: '#808080'},duration);
     }, delay);
   }

    // ask pi for settings on startup
    function requestSettings(){
      socket.emit('msgEvent',{msg:"request"});
    }

    function setSensitivity(event, direction){
      var thisBlock = event.parentElement.parentElement;
      var sensitivity = $(thisBlock).find("#sensitivity")[0].innerHTML;
      if(direction === "up" && sensitivity < 100) sensitivity++;
      if(direction === "down" && sensitivity > 0) sensitivity--;
      $(thisBlock).find("#sensitivity").text(sensitivity); // to fix
    }

    function updateButton(){
      updateServer();
      socket.emit('msgEvent',{msg:"reloadSpeech"});
      var i = 0;
      $('#blocks').children('.block').each(function () {
        $this = $(this);
        animateblock($this, i, 500)
        i += 100;
    });
  }

    // copy the current blocks values into a settings file and send it to the pi
    function updateServer(){
      var keyphrase = [];
      $('#blocks').children('.block').each(function () {
        var name = $(this).find('input').val(); // "this" is the current element in the loop
        var whisper = $(this).find('textarea').val();
        var sensitivity = $(this).find('#sensitivity')[0].innerHTML;

        keyphrase.push({"name":name ,"whisper":whisper, "sensitivity":sensitivity});
      });

      var setting = {"noise": $("#noise").prop('checked'),
                     "language": $("#language").val(),
                     "gender": $("#gender").val(),
                     "volume": $("#setting-volume").val(),
                     "delay": $("#setting-delay").val()}

      socket.emit('msgEvent',{msg:"updateServer", data: {keyphrase, setting}});
    }

    //prevent scroll on phone
    function preventBehavior(e) {
      e.preventDefault();
    };

    // update blocks on start up
    function updateBlocks(obj){

      var base = $("#blocks").children().first();
      base.find('input').val(obj.keyphrase[0].name);
      base.find('textarea').val(obj.keyphrase[0].whisper);

      base.find("#sensitivity").text(obj.keyphrase[0].sensitivity); // to fix
      if(obj.keyphrase.length > 1){
        for(var i=1; i< obj.keyphrase.length; i++){
          addDefinedBlock(obj.keyphrase[i].name, obj.keyphrase[i].whisper, obj.keyphrase[i].sensitivity);
        }
      }
    }

    function updateSettings(msg){

      var set = currentSettings.setting;

      $("#noise").val(set.noise);
      $("#language").val(set.language);
      $("#gender").val(set.gender);

      $("#setting-volume").val(set.volume);
      $("#setting-volume").parent().find('.setting-value')[0].innerHTML = set.volume;

      $("#setting-delay").val(set.delay);
      $("#setting-delay").parent().find('.setting-value')[0].innerHTML = set.delay;

    }

    function addDefinedBlock(input,output,sen){
      $("#base_block").clone().appendTo("#blocks");
      var new_block = $("#blocks").children().last();

      new_block.find('img').css("display", "block");

      new_block.find('input').val(input);
      new_block.find('textarea').val(output);
      new_block.find("#sensitivity").text(sen)
      //new_block.find('input').attr("placeholder", input);
      //new_block.find('textarea').attr("placeholder", output);
      checkInput(new_block.find('textarea')[0]);
    }

    // add new block with random trigger
    function addNewBlock(){
      //var r = Math.floor(Math.random() * (premadeCommands.length - 0));
      addDefinedBlock("","",20);
      //$('#blocks').children('.block').last().find('input').focus();
    }


    // this changes the displayed value on sliding motion
    $('.slider').on("input", function (e) {
      $(this.parentElement).find('.setting-value')[0].innerHTML = this.value;
    });

    // these updatesd the settings when realeasing the slider
    $('#setting-volume').change(function(e){
      updateServer();
      socket.emit('msgEvent',{msg:"volumeChange"});
    });

    $('#setting-delay').change(function(e){
      updateServer();
      socket.emit('msgEvent',{msg:"delayChange"});
    });

    $('#noise').change(function(e){
      updateServer();
      socket.emit('msgEvent',{msg:"noiseChanged"});
    });

    $('#language').change(function(e){
      updateServer();
      socket.emit('msgEvent',{msg:"languageChanged"});
    });

    $('#gender').change(function(e){
      updateServer();
      socket.emit('msgEvent',{msg:"genderChanged"});
    });

    $('#setting-default').click(function(e){

      $("#noise").val(true);
      $("#language").val("English");
      $("#gender").val("Female");

      $("#setting-volume").val(20);
      $("#setting-volume").parent().find('.setting-value')[0].innerHTML = 20;

      $("#setting-delay").val(10);
      $("#setting-delay").parent().find('.setting-value')[0].innerHTML = 10;

      updateServer();

    });

    function removeBlock(event){
      var block = event.parentElement;
      block.remove();
    }

    function checkInput(obj){
      var letters = obj.value.length
      if(letters < 1) letters = 1;
      var input_w = $("#base_block").width();
      var max_letters = input_w / 11;
      var rows = Math.ceil(letters/ max_letters);
      obj.rows = rows;
    }

    function openSettings(){
      //$("#settings").animate({height: '100%'});
      $("#settings").css('display', 'block');
    }
    function closeSettings(){
      //$("#settings").animate({height: '0%'});
      $("#settings").css('display', 'none');
      socket.emit('msgEvent',{msg:"reloadSpeech"});
    }

    var premadeCommands = [
      {
        "input": "Weather man",
        "output": "Ok Google, how is the weather today"
      },
      {
        "input": "Funky Time",
        "output": "Ok Google, play some funky music on spotify"
      },
      {
        "input": "Gandalf",
        "output": "Ok Google, where is the hobbits?"
      },
      {
        "input": "Pizza Time",
        "output": "Ok Google, order a pizza"
      },
      {
        "input": "Marvin",
        "output": "Ok Google"
      }
    ];

   // document.addEventListener("touchmove", preventBehavior, {passive: false});
  </script>
</html>
